<template>
<div>

  <div class="kefu" @click="go_isshow" v-if="hashow">客服</div>
  <div class="container"  v-show="isSHow">
    <!-- <v-header class="cx-ym"></v-header> -->
    <div class="conty">
      <div class="left">
        <!-- <input v-model="input" type="text" placeholder="搜索"> -->
        <h6></h6>
        <ul>
          <li :class="{active:isActive==index}" v-for="(item,index) in getData" :key="index" @click="setItem(index)">
            <el-badge :is-dot='item.isTop' class="item">
              <img :src="item.latestMessage.content.user.portrait||'https://assets.chuangxu.cn/image/header.jpg'" alt="">
            </el-badge>
            <!-- <img :src="item.latestMessage.content.user.portrait||'http://assets.chuangxu.cn/image/header.jpg'" alt=""> -->
            <p>{{item.latestMessage.content.user.name||'/'}}</p>
          </li>
        </ul>
      </div>
      <div class="right">
        <div style="display:flex;align-items: center;justify-content: space-between;">
          <h6 v-if='getData.length>0'>{{getData[isActive].latestMessage.content.user.name}}</h6>
          <i class="el-icon-remove" @click="go_close" style="margin-right:20px;"></i>
        </div>
        <ul id="chatContainer">
          <li v-for="(items,indexs) in getMsg" :key="indexs">
            <div class="contl" v-if="items.messageDirection==2">
              <img class="active" :src="items.content.user.portrait||'https://assets.chuangxu.cn/image/header.jpg'" alt="">
              <p v-if="items.messageType=='TextMessage'">{{items.content.content}}</p>
              <img class="gif" v-if="items.messageType=='ImageMessage'" :src="items.content.imageUri" alt="">
              <a :href="items.content.fileUrl" v-if="items.messageType=='FileMessage'">
                <h1>文件</h1>
                <h2>{{items.content.name}}</h2>
              </a>
            </div>
            <div class="contr" v-else>
              <img class="active" src="https://assets.chuangxu.cn/image/header.jpg" alt="">
              <p v-if="items.messageType=='TextMessage'">{{items.content.content}}</p>
              <img class="gif" v-if="items.messageType=='ImageMessage'" :src="items.content.imageUri" alt="">
              <a :href="items.content.fileUrl" v-if="items.messageType=='FileMessage'">
                <h1>文件</h1>
                <h2>{{items.content.name}}</h2>
              </a>
            </div>
          </li>
        </ul>
        <div class="foot">
          <input type="text" v-model="value" @keyup.enter="go_send">
          <div>
            <input type="file" @change="go_thisflie($event)" accept=".xls,.doc,.txt,.pdf,.png,.jpeg,.jpg,.tiff,.docx">
            <i @click="go_file" class="iconfont">&#xe75b;</i>
          </div>
          <i @click="go_send" class="iconfont active">&#xe75a;</i>
        </div>
      </div>

    </div>
  </div>
</div>
</template>

<script>
// import Header from "../public/Header.vue";
import store from "@/vuex/store.js";
import { Notification } from 'element-ui';
export default {
  data() {
    return {
      hashow:false,
      input:'',//搜索
      getData:[],//会话列表
      isActive: 0,//确认对话
      getMsg:[],//获取某个会话
      allMsg:[],//所有会话
      value:'',//发送的内容
      id:'',//现在的id
      frequency:true,//频率

      isSHow:false,//是否显示对话框
    };
  },
  store,
  created() {
    if(JSON.parse(sessionStorage.getItem('userinfo')).roles.find(item=>item.slug=='service')){
      this.hashow = true
      let _this = this
      function setlogin() {
        return new Promise(function(resolve, reject) {
          // const s = document.createElement("script");
          // s.type = "text/javascript";
          // s.src = "https://cdn.ronghub.com/RongIMLib-2.3.5.min.js";
          // document.body.appendChild(s);
          
          const r = document.createElement("script");
          r.type = "text/javascript";
          r.src = "https://assets.chuangxu.cn/js/rongcloud/qiniu.js";
          document.body.appendChild(r);
          const o = document.createElement("script");
          o.type = "text/javascript";
          o.src = "https://assets.chuangxu.cn/js/rongcloud/upload.js";
          document.body.appendChild(o);
          const n = document.createElement("script");
          n.type = "text/javascript";
          n.src = "https://assets.chuangxu.cn/js/rongcloud/init.js";
          document.body.appendChild(n);
          setTimeout(function() {
            resolve("110");
          }, 500);
        });
      }
      setlogin().then(res => {
        RongIMClient.init("0vnjpoad06dkz"); //这是初始化，需要填参数就是你的APPKEY。这个不难理解。
        var token = JSON.parse(sessionStorage.getItem('userinfo')).im_token;// 连接融云服务器。
        RongIMClient.connect(
          token,
          {
            onSuccess: function(userId) {
              console.log("Login successfully." + userId);
              //userId是申请token时的填写的id，到时候可以封装在下面的extra中传过去
  
              // RongIMClient.getInstance().removeConversation(RongIMLib.ConversationType.PRIVATE, "1d358796-316e-46d2-8e3b-a2cc16737003", { 
              //   onSuccess:function(result){ 
              //           console.log("删除会话成功");
              //   }, 
              //   onError:function(error){ 
              //   // error => 清除会话错误码。 
              //       showResult("删除会话失败",error,start);
              //   } 
              // });
              // RongIMClient.getInstance().getFileToken(RongIMLib.FileType.IMAGE, {
              //     onSuccess: function(data){
              //         console.log(data)
              //     },
              //     onError: function(error){
                      
              //     }
              // }); 
              RongIMClient.getInstance().getConversationList(
                {
                  onSuccess: function(list) {
                    var title = "成功获取 " + list.length + " 个会话";
                    sessionStorage.setItem('cxlist',JSON.stringify(list));
                    _this.getData = JSON.parse(sessionStorage.getItem("cxlist"));
                    console.log(_this.getData)
                    _this.setItem(0)
                  },
                  onError: function(error) {
                    console.log("获取会话失败");
                  }
                },
                null
              );
            },
            onTokenIncorrect: function() {
              console.log("token无效");
            },
            onError: function(errorCode) {
              var info = "";
              switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                  info = "超时";
                  //链接超时进行重新的链接start
                  var callback = {
                    onSuccess: function(userId) {
                      console.log("Reconnect successfully." + userId);
                    },
                    onTokenIncorrect: function() {
                      console.log("token无效");
                    },
                    onError: function(errorCode) {
                      console.log(errorcode);
                    }
                  };
                  var config = {
                    // 默认 false, true 启用自动重连，启用则为必选参数
                    auto: true,
                    // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
                    url: "cdn.ronghub.com/RongIMLib-2.2.6.min.js",
                    // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
                    rate: [100, 1000, 3000, 6000, 10000]
                  };
                  RongIMClient.reconnect(callback, config);
                  //链接超时进行重新链接end
                  break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                  info = "未知错误";
                  break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                  info = "不可接受的协议版本";
                  break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                  info = "appkey不正确";
                  break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                  info = "服务器不可用";
                  break;
              }
              console.log(errorCode);
            }
          }
        );
        // 设置连接监听状态 （ status 标识当前连接状态 ）
        // 连接状态监听器
        RongIMClient.setConnectionStatusListener({
          onChanged: function(status) {
            switch (status) {
              case RongIMLib.ConnectionStatus.CONNECTED:
                console.log("链接成功");
                break;
              case RongIMLib.ConnectionStatus.CONNECTING:
                console.log("正在链接");
                break;
              case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log("断开连接");
                break;
              case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                console.log("其他设备登录");
                break;
              case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log("域名不正确");
                break;
              case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log("网络不可用");
                break;
            }
          }
        });
        // 消息监听器
        RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: function(message) {
            // 判断消息类型
            console.log(message)
            var num = _this.getData.findIndex(item=>item.latestMessage.content.user.id==message.targetId)
            if(num!=_this.isActive&&(message.content.content||message.content.fileUrl)){
              _this.getData[num].isTop = true
              if(_this.allMsg[num]){
                _this.allMsg[num].push(message)
              }
            }
            if(num==_this.isActive&&(message.content.content||message.content.fileUrl)){
              _this.getMsg.push(message)
              _this.allMsg[num] = _this.getMsg
            }
            switch (message.messageType) {
              case RongIMClient.MessageType.TextMessage:
                // message.content.content => 消息内容
                console.log(message);
                // $(".content_box").text(message.content.content)
                break;
              case RongIMClient.MessageType.VoiceMessage:
                // 对声音进行预加载
                // message.content.content 格式为 AMR 格式的 base64 码
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.ImageMessage:
                // message.content.content => 图片缩略图 base64。
                // message.content.imageUri => 原图 URL。
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.DiscussionNotificationMessage:
                // message.content.extension => 讨论组中的人员。
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.LocationMessage:
                // message.content.latiude => 纬度。
                // message.content.longitude => 经度。
                // message.content.content => 位置图片 base64。
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.RichContentMessage:
                // message.content.content => 文本消息内容。
                // message.content.imageUri => 图片 base64。
                // message.content.url => 原图 URL。
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.InformationNotificationMessage:
                // do something...
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.ContactNotificationMessage:
                // do something...
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.ProfileNotificationMessage:
                // do something...
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.CommandNotificationMessage:
                // do something...
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.CommandMessage:
                // do something...
                console.log(message.content.content);
                break;
              case RongIMClient.MessageType.UnknownMessage:
                console.log(message.content.content);
                // do something...
                break;
              default:
                console.log(message.content.content);
              // do something...
            }
            _this.getData.push('')
            _this.getData.pop()
          }
        });
      });
    }
  },
  mounted() {
    store.commit("changehref", 8);
  },
  watch: {
    getMsg() {
        this.change()
    },
    value(res){
      if(this.frequency){
        if(res){
          var conversationType = RongIMLib.ConversationType.PRIVATE;//只有单聊有正在输入状态。
          var targetId = this.id;
          var msgName = "TextMessage";//用户正在输入的消息类型 VoiceMessage等。
          this.frequency = false
          RongIMClient.getInstance().sendTypingStatusMessage(conversationType, targetId, msgName, {
              onSuccess: function (message) {
                  console.log("Send successfully");
              },
              onError: function (errorCode,message) {
                  console.log('发送失败:' + info);
              }
          });
        }
      }
      if(res == ''){
        this.frequency = true
        var conversationType = RongIMLib.ConversationType.PRIVATE;//只有单聊有正在输入状态。
        var targetId = this.id;
        var msgName = "VoiceMessage";//用户正在输入的消息类型 VoiceMessage等。
        RongIMClient.getInstance().sendTypingStatusMessage(conversationType, targetId, msgName, {
            onSuccess: function (message) {
                console.log("Send successfully");
            },
            onError: function (errorCode,message) {
                console.log('发送失败:' + info);
            }
        });
      }
    }
  },
  methods: {
    go_close(){
      this.isSHow = false
    },
    go_isshow(){
      this.isSHow = true
    },
    change(){
      this.$nextTick(() => {
        var container = this.$el.querySelector("#chatContainer");
        container.scrollTop = container.scrollHeight;
      })
    },
    go_file(){

    },
    //选择图片或者文件
    go_thisflie(event){
      let _this = this
      var im = RongIMClient.getInstance();
      var urlItem = {
        file: function(data){
          var fileType = RongIMLib.FileType.FILE;
          im.getFileUrl(fileType, data.filename, data.name, {
            onSuccess: function(result){
              data.downloadUrl = result.downloadUrl;
              console.log(data)
              sendMsg(data)
            },
            onError: function(error){
              showResult('getFileToken error:' + error);
            }
          });
        },
        image: function(data){
          var fileType = RongIMLib.FileType.IMAGE;
          im.getFileUrl(fileType, data.filename, null, {
            onSuccess: function(result){
              data.downloadUrl = result.downloadUrl;
              sendMsg(data)
            },
            onError: function(error){
              showResult('getFileToken error:' + error);
            }
          });
        }
      };

      var getFileUrl = function(data){
        urlItem[data.fileType](data);
      };
      var getFileType = function(filename){
        // 默认支持两种图片格式，可自行扩展
        var imageType = {
          'jpg': 1,
          'png': 2
        };
        var index = filename.lastIndexOf('.') + 1,
          type = filename.substring(index);
        return type in imageType ? 'image': 'file';
      };

      var sendMsg = function(data){
        // 发送文件or图片消息
        if(data.fileType=="image"){
          function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var dataURL = canvas.toDataURL("image/png");
            dataURL = dataURL.split('base64,')[1];
            return dataURL
          }
          var img=new Image;
          img.crossOrigin="anonymous";
          img.src = data.downloadUrl;
          img.onload = function () {
            var datay = getBase64Image(img);

            var msg = new RongIMLib.ImageMessage({
              imageUri: data.downloadUrl, 
              content: datay,
              user:{
                id:_this.getData[_this.isActive].latestMessage.content.user.id,
                name:_this.getData[_this.isActive].latestMessage.content.user.name,
                portrait:_this.getData[_this.isActive].latestMessage.content.user.portrait||'https://assets.chuangxu.cn/image/header.jpg'
              }
            });
            RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.PRIVATE, _this.id, msg, {
              onSuccess: function (message) {
                _this.getMsg.push(message)
              },
              onError: function (errorCode,message) {
                console.log('发送失败')
              }
            })
          }
          
        }else if(data.fileType=="file"){

          var msg = new RongIMLib.FileMessage({
            name: data.name, // 文件名称
            size:1024,
            type:'js',
            fileUrl: data.downloadUrl, // 文件地址
            user:{
              id:_this.getData[_this.isActive].latestMessage.content.user.id,
              name:_this.getData[_this.isActive].latestMessage.content.user.name,
              portrait:_this.getData[_this.isActive].latestMessage.content.user.portrait||'https://assets.chuangxu.cn/image/header.jpg'
            }
          });
          RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.PRIVATE, _this.id, msg, {
            onSuccess: function (message) {
              _this.getMsg.push(message)
            },
            onError: function (errorCode,message) {
              console.log('发送失败')
            }
          })
        }
      }

      var callback = {
        onError	: function (errorCode) { 
          showResult(errorCode);
        },
        onProgress : function (loaded, total) {
          var percent = Math.floor(loaded/total*100);
        },
        onCompleted : function (data) { 
          data.fileType = getFileType(data.name);
          getFileUrl(data);
          console.log(data)
        } 
      };

      var config = { 
        domain: 'https://upload.qiniu.com',
        fileType: RongIMLib.FileType.IMAGE,
        getToken: function(callback){
          im.getFileToken(this.fileType, {
            onSuccess: function(data){
              // console.log(data)
              callback(data.token);
            },
            onError: function(error){
              showResult('getFileToken error:' + error);
            }
          });
        }
      };

      var initType = {
        file: function(_file){
          config.fileType = RongIMLib.FileType.FILE;
          UploadClient.initFile(config, function(uploadFile){
            // console.log(uploadFile)
            uploadFile.upload(_file, callback);
          });
        },
        image: function(_file){
          UploadClient.initImage(config, function(uploadFile){
            uploadFile.upload(_file, callback);
          });
        }
      };

      var _file = event.target.files[0];
      initType[getFileType(_file.name)](_file);
    },
    //获取会话
    setItem(index){
      let _this = this
      this.isActive = index
      this.getData[index].isTop = false
      this.id = this.getData[index].targetId
      if(_this.allMsg[index]){
        _this.getMsg = _this.allMsg[index]
      }else{
        RongIMClient.getInstance().getHistoryMessages(RongIMLib.ConversationType.PRIVATE, this.getData[index].targetId, null, 20, {
          onSuccess: function(list, hasMsg) {
            _this.getMsg = list
            // this.getMessage.push(' ')
            // this.getMessage.pop()
            _this.allMsg[index] = list
            console.log(_this.getMsg)
          },
          onError: function(error) {
            console.log('获取失败')
          }
        });
      }
    },
    //发送消息
    go_send(){
      let _this = this
      if(this.value){
        var msg = new RongIMLib.TextMessage({
          content:this.value,
          user:{
            id:this.getData[this.isActive].latestMessage.content.user.id,
            name:this.getData[this.isActive].latestMessage.content.user.name,
            portrait:this.getData[this.isActive].latestMessage.content.user.portrait||'https://assets.chuangxu.cn/image/header.jpg'
          }
        });

        var conversationtype = RongIMLib.ConversationType.PRIVATE; // 私聊
        var targetId = this.id; // 目标 Id

        RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
          // 发送消息成功
          onSuccess: function (message) {
            _this.getMsg.push(message)
            _this.value = ''
            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
            console.log("Send successfully");
          },
          onError: function ( message) {
            console.log('发送失败:');
          }
        });
      }else{
        Notification({
          title:'提示',
          message:"请输入内容",
          type:'info'
        })
      }
    }
  }
};
</script>

<style lang='scss' scoped>
@import '../../assets/css/iconfonta.css';
.kefu{
  width:50px;
  height:50px;
  background:rgba(40,178,254,1);
  border-radius:10px;
  font-size: 16px;
  position: fixed;
  bottom: 20px;
  right: 20px;
  line-height: 50px;
  text-align: center;
  color: #fff;
  cursor: pointer;
  &:hover{
    background: #0087e0;
  }
}
.container {
  width: 708px;
  height: 512px;
  background:rgba(248,248,248,1);
  box-shadow:0px 0px 24px 0px rgba(0,0,0,0.14);
  border:1px solid rgba(230,230,230,1);
  position: fixed;
  bottom: 0;
  right: 0;
  .cx-ym {
    width: 100%;
    height: calc(100% - 110px);
  }
  .conty{
    width: 1200px;
    margin: auto;
    display: flex;
    .left{
      width: 200px;
      margin-top: 40px;
      input{
        width: 200px;
        height: 32px;
        background: #E6E6E6;
        border: none;
        padding: 0 10px;
        box-sizing: border-box;
      }
      h6{
        width: 200px;
        height: 1px;
        background: #D2D2D2;
        margin: 20px 0px;
      }
      ul{
        height: 434px;
        overflow-x: hidden;
        overflow-y: auto;
        li{
          width: 200px;
          height: 50px;
          display: flex;
          cursor: pointer;
          align-items: center;
          img{
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-left: 10px;
          }
          p{
            font-size: 14px;
            margin-left: 24px;
          }
          &.active{
            background: #F5F5F5;
          }
        }
      }
    }
    .right{
      margin-left: 8px;
      color: #515151;
      h6{
        font-size: 24px;
        line-height: 60px;
      }
      ul{
        // margin-top: 42px;
        height: 416px;
        overflow-y: auto;
        background: #fff;
        li{
          width: 480px;
          margin-bottom: 26px;
          a{
            width: 282px;
            height: 66px;
            display: flex;
            background: #F8F8F8;
            margin: 0 20px;
            align-items: center;
            text-decoration: none;
            border-radius: 10px;
            h1{
              width:53px;
              height:53px;
              background:rgba(40,178,254,1);
              color: #fff;
              text-align: center;
              line-height: 53px;
              margin-left: 10px;
            }
            h2{
              color: #515151;
              width: 198px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          div{
            display: flex;
            img.active{
              width: 30px;
              height: 30px;
              border-radius: 50%;
              align-items: flex-start;
            }
            img.gif{
              width: 200px;
              height: 100px;
              margin-left: 20px;
              display: block;
            }
            p{
              padding: 8px;
              line-height: 20px;
              font-size: 14px;
              color: #515151;
              background: #F3F3F3;
              margin-left: 20px;
              border-radius: 5px;
            }
            &.contr{
              display: flex;
              flex-direction: row-reverse;
              p{
                margin-right: 20px;
                margin-left: 0px;
              }
            }
          }
        }
      }
      .foot{
        width: 500px;
        height: 36px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        >input{
          width: 470px;
          height: 36px;
          background: #E6E6E6;
          border: none;
          outline: none;
          box-sizing: border-box;
          padding: 0 10px;
          border-radius: 5px;
        }
        i,div{
          margin-left: 10px;
          width: 24px;
          height: 24px;
          padding: 6px;
          background: #515151;
          color: #fff;
          font-size: 22px;
          border-radius: 5px;
          cursor: pointer;
          position: relative;
          &.active{
            background: #28B2FE;
          }
        }
        
        div{
          i{
            position: absolute;
            top: 0px;
            left: -10px;
            z-index: 1;
          }
          input{
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 2;
            opacity: 0;
          }
        }
      }
    }
  }
}
</style>